package batch.ecircle;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.*;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.*;
import java.io.*;
import java.util.Date;
import java.security.*;

public class MakeXmasUserFileForGbr
{
    final String TODAY = DateFormatUtils.format(new Date(), "yyyyMMdd");
    
	String today = "";
    String strCountry = "";     //Which Country
    String strSplit   = "";     //Separate file or Not
    String strFileGB  = "";

    public MakeXmasUserFileForGbr(String strPrCountry, String strPrSplit, String strToday) {
        strCountry 	= (strPrCountry.equals("all")) ? "" : StringUtils.defaultString(strPrCountry);
        today 		= StringUtils.defaultString(strToday, TODAY);
        strSplit   	= StringUtils.defaultString(strPrSplit);
    }

    public static void main(String [] args) {
        Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info("( * ) Start.");

        MakeXmasUserFileForGbr mkUser = null;

        if( args.length == 3 ){
            mkUser = new MakeXmasUserFileForGbr(args[0], args[1], args[2]);
        }
        else{
            System.exit(-1);
        }

        mkUser.startMake();

        Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info("( * ) End.");
    }

    //Make a log file and a data file.
    public void startMake(){
        Connection   conn = null;
        Statement    stmt = null;
        ResultSet    rs   = null;
        OutputStreamWriter oswFile = null;

        String fileNm  = "/home01/sfc/batch/ecircle/data/daily_email_" + today + ".csv";
        
        int cnt = 0;
        int rsCnt = 0;

        String sUserNo = "";
        String sMD5 = "";

        StringBuffer sbTemp = new StringBuffer();

        StringBuffer sQuery = new StringBuffer()
                             .append("SELECT A.EMAIL                                	\n")
                             .append("     , DECODE(A.FIRSTNAME, 'WAP_TEMP', 'member' 	\n")
                             .append("                         , 'SIM_TEMP', 'member' 	\n")
                             .append("                         , ''        , 'member' 	\n")
                             .append("                         , NULL      , 'member' 	\n")
                             .append("                         , A.FIRSTNAME) FIRSTNAME	\n")
                             .append("  FROM G_MB_MEMBER A                            	\n")
                             .append("     , G_PR_OPTIN_OPTOUT  B                     	\n")
                             .append(" WHERE A.USER_NO      =  B.USER_NO              	\n")
                             .append("   AND A.REG_COUNTRY  =  '" + strCountry + "'   	\n")
                             .append("   AND A.DELETED      IS NULL                   	\n")
                             .append("   AND B.OPTINOUT		='Y'						\n");

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@eu-anydb:1521:ORAEU", "gsms", "any02gs");
            //conn = DriverManager.getConnection("jdbc:oracle:thin:@eu-stgdb:1521:ORAEU","gsms","any02gs");
            
            conn.setAutoCommit(true);
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sQuery.toString());
			rsCnt = rs.getMetaData().getColumnCount();

            oswFile = new OutputStreamWriter(new FileOutputStream(fileNm, false), "ISO-8859-1");

            MessageDigest md5 = MessageDigest.getInstance("MD5");

            
			sbTemp.setLength(0);
        	sbTemp.append("user.Email,user.Firstname\n");
            oswFile.write(sbTemp.toString());
            
            while(rs.next()){
				sbTemp.setLength(0);

                for(int i=1;i<=rsCnt;i++) {
                    sbTemp.append(ObjectUtils.toString(rs.getObject(i), ""));

                    if( i == rsCnt ){
                        sbTemp.append("\n");
                    }
                    else{
                        sbTemp.append(",");
                    }
                }

                oswFile.write(sbTemp.toString());
                cnt++;

                if(cnt % 500 == 0){
                    Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info("here we are == " + cnt);
                }
            }

            Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info("Total Count : " + cnt);
        }
        catch(Exception ex) {
            ex.printStackTrace();

            Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info(ex.toString());
            StackTraceElement[] stElement = ex.getStackTrace();
            for(int p=0; p<stElement.length;p++){
                Logger.getLogger("ecircle.MakeXmasUserFileForGbr").info(stElement[p].toString());
            }
        }
        finally {
            if (rs   != null) try { rs.close(); }   catch (Exception e) { e.printStackTrace(); }
            if (stmt != null) try { stmt.close(); } catch (Exception e) { e.printStackTrace(); }
            if (conn != null) try { conn.close(); } catch (Exception e) { e.printStackTrace(); }
            if (oswFile != null) try { oswFile.close(); } catch (Exception e) { e.printStackTrace(); }
        }
    }

    private String bytesToHex(byte[] b) {
        char hexDigit[] = {
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'a', 'b', 'c', 'd', 'e', 'f'
		};

		StringBuffer buf = new StringBuffer();
		for (int i=0 ; i<b.length ; i++) {
		    buf.append(hexDigit[b[i] >> 4 & 0xf]);
		    buf.append(hexDigit[b[i] & 0xf]);
		}

		return buf.toString();
    }
}
